<?php
class DoAction extends CoreAction{

	var $credit;
	
	function _initialize(){
		parent::_initialize();
		$this->credit = Model('UserCredit');
	}
	
	
    public function subscibeCate(){
    	$content = json_decode($_POST['subId']);
    	echo service('Follow')->addFollowData($content,'bbs');
    }
    
    public function deleteSubscibeCate(){
    	$cid = h($_POST['subId']);
    	echo service('Follow')->delFollowData($cid,'bbs');
    }
	
	//添加主题
	function post() {
		/** 附件检测 **/
		$list = X('Xattach')->getAttach($_POST['attach']);
		unset($_POST['Xattach']);
		foreach($list as $key=>$value){
			$_POST['attach'][$key]   = $value['id'].'|'.$value['name'];
		}

		$_POST['title'] = htmlspecialchars($_POST['title'], ENT_QUOTES);
		$content  =  $_POST['content'] ;
		$this->class = trim( $_POST['board'] );
		if ( $this->topic->create() ){
				if($_POST['attach']){ //添加附件
					$this->topic->attach = 1;   
				}
				$this->topic->tags	    =	$this->topic->getTags( $_POST['tags'] );
				$class = explode( ',' ,$this->class );
				$this->topic->tagid  = end($class);
				$this->topic->board  = $this->class;
				$this->topic->class1 = intval( $class[0] );
				$this->topic->class2 = intval( $class[1] );
				$this->topic->class3 = intval( $class[2] );		
				$this->topic->uid	    = $this->mid;
				$this->topic->cTime     = time();
				$this->topic->rTime     = time();
				$this->topic->lastreuid = $this->mid;
				//投票贴
				$is_valid_vote = M('vote')->where('id='.intval($_POST['vote_id']))->limit(1)->findAll();
				$this->topic->type		= isset($_POST['vote_id']) && $is_valid_vote ? 1 : 0;

				if($tid = $this->topic->add()) {
					import('ORG.Net.IpLocation');   //添加回复
					$ip = new IpLocation();
					$this->post->create();
					$this->post->uid     = $this->mid;
					$this->post->tid     = $tid;
					$this->post->title   = $_POST['title'];
					$this->post->content = $content;
					$this->post->istopic = 1;
					$this->post->ip      = $ip->get_client_ip();
					$this->post->cTime   = time();
			    	$this->post->attach  = serialize($this->__parseAttach($_POST['attach']));
					$result = $this->post->add();
					
					//投票
					isset($_POST['vote_id']) && $is_valid_vote && M('vote')->where('id='.$_POST['vote_id'])->setField('fieldId', $tid);

					//积分
					$this->credit->set($this->mid,'bbs_topic_post');
					
					//添加动态
					$title['pid']    = $result;
   					$title['tid']   = $tid;
   					$title['gid']   = $this->_gid;
   					$title['title'] = msubstr($_POST['title'],0,30);;
   					$title['board'] = end( $this->getTopNav( $this->class , true ) );
					$body['info']   = msubstr(strip_tags($content),0,100);
   					$body['tid']    = $tid;					
   					$body['pid']    = $result;					
					x('Feed')->put( 'bbs_topic',$title,$body );
					
					if($_POST['transcribeuid']){
						x('Notify')->put('bbs_transcribe',$_POST['transcribeuid'],$title,$body);
					}
					
					if( $_POST['transcribeuname'] ){
						$this->sendEmail($_POST['transcribeuname'],$title,$body['info'] );
					}
					
					//TODO 跳转会插入两条数据，需解决
					redirect(U('bbs/Index/forumlist',array( 'class'=>$this->class )));
					//$this->assign('jumpUrl',U('bbs/Index/forumlist',array('class'=>$_POST['category'])) );
					//$this->success('添加成功');									
				}else{
					$this->error( L('do_thread_add_error') );
				}
		}else{
			$this->error( $this->topic->getError() );
		}
	}
	
	protected function sendEmail($uname,$title,$content){
			$service = service("Mail");
			//四个参数分别为：收件人地址、主题、内容，发件人信息
			//第四个参数（发件人信息）为空时，使用系统帐户
			$name = getUserName($this->mid);
			$senderUser = explode(',',$uname);
			foreach ( $senderUser as $key=>$value){
				$senderUser[$key] = $value.'@notesmail.huawei.com';
			}
			$senderInfo = array(
			   'name' => $name,
			   'email'=> getUserEmail($this->mid),
			);
			
			$actor = $name;
			$url   = U('bbs/Index/detail',array('id'=>$title['tid']));
			$title = "{$actor} ".L('do_invite_talk')."   {$title['title']}";
			
			$data['title'] = $title['title'];
			$data['body']  = "<div class='C_C'>{$content}</div><div class='R_att'><a href={$url}>参与讨论</a></div>";
			
			
			$body = $this->__getEmailBody($data,$name,$this->mid);
			$title = "hi:".$title;
			$result = $service->send_email($senderUser,$title,$body,$senderInfo);
			return $result;
	}	
	
	protected function __getEmailBody($data,$uname,$uid){
		$css = '<link href="'.SITE_URL.'/public/themes/blue/layout.css" rel="stylesheet" type="text/css" />';
		$path = SITE_URL;
		$url = U('space/view/index','uid='.$uid);
		$temp_html = <<<EOT
{$css}
<div style="color:#000;font-size:12px;">
Dear:<br />
&nbsp;&nbsp;&nbsp;&nbsp;{$data['title']}

<div style="margin-left: 30px;">
{$data['body']}
</div>
<a href="{$url}">{$uname}</a><br />

=============================================================================<br />
&nbsp;&nbsp;&nbsp;&nbsp;“热爱分享，畅想成长”<br />
&nbsp;&nbsp;&nbsp;&nbsp;知识共享平台：<a href="{$path}">{$path}</a><br />
=============================================================================
</div>
EOT;
		$aBody = $temp_html;
		$aBody = str_replace("<a","<a style='color:#000;'",$temp_html);
		return $aBody;
	}
			
	function reply(){
		$tid = isset($_POST['tid']) ? intval($_POST['tid']) : 0;
		$topic = $this->topic->getTopic( $tid ); 
		if(!$topic['id']){
			$this->error( L('do_post_wrong') );
			exit;
		}elseif($topic['lock']==1){
			$this->error( L('do_post_wrong_islock') );
			exit;
		}

		/** 附件检测 **/
		$list = X('Xattach')->getAttach($_POST['attach']);
		unset($_POST['Xattach']);
		foreach($list as $key=>$value){
			$_POST['attach'][$key]   = $value['id'].'|'.$value['name'];
		}			
		
		$this->class = $topic['board'];
		
		//执行回复操作
		$content = h($_POST['content']);
		if( strlen( $content ) <5 ) $this->error( L('do_post_content_lt') );
		import('ORG.Net.IpLocation');
		$ip = new IpLocation();
		$this->post->create();
		$this->post->tid     = $topic['id'];
		$this->post->uid     = $this->mid;
		$this->post->quote   = intval( $_POST['quote'] );
		$this->post->content = $content;
		$this->post->title   = htmlspecialchars( $_POST['title'],ENT_QUOTES );
		$this->post->ip      = $ip->get_client_ip();
		$this->post->cTime   = time();
		$this->post->attach  = serialize($this->__parseAttach($_POST['attach']));
		$result = $this->post->add();
		if($result){
			//积分
			$this->credit->set($this->mid,'bbs_post_reply');
			
			$data['rTime']      = time();
			$data['lastreuid']  = $this->mid;
			$data['replycount']  = $topic['replycount']+1;
			$this->topic->where('id='.$topic['id'])->data($data)->save();
			
			$title['pid']        = $result;
			$title['groupname'] = $this->_Core['groupInfo']['name'] ;
			$title['tid']       = $topic['id'] ;
			$title['title']     = $topic['title'] ;
			$title['board']     = implode( " >> ", $this->getTopNav( $this->class , true ) );
			$body['tid']        = $topic['id'] ;
			$body['content']    = msubstr(getQuoteContent($content),0,50);	
			$body['pid']        = $result;
			if($_POST['pid']){
				$info = $this->post->where('id='.intval($_POST['pid']))->field('uid')->find();
			}else{
				$info['uid']     = $topic['uid'];
				$info['istopic'] = 1;
			}
			

			if($info['uid'] != $this->mid ){
				if($_POST['quote']){
					X('Notify')->put('bbs_quote',$info['uid'],$title,$body);
				}else{
					if( $info['istopic'] ){
						X('Notify')->put('bbs_reply',$topic['uid'],$title,$body);
					}else{
						X('Notify')->put('bbs_reply_post',$info['uid'],$title,$body);
					}
				};
			}
		}
		$this->assign('jumpUrl',U('bbs/Index/detail',array('id'=>$tid,'p'=>'last')).'#p'.$result);
		$this->success( L('do_post_success') );
	}
	
	function doedit(){		
		$intPid = intval( $_POST['pid'] );
		$data['postInfo'] = $this->post->getPostInfo( $intPid );
		
		/** 权限控制  **/
		$this->class = $data['postInfo']['board'];
		$this->boardPurview();   //载入权限控制器
		if(!$this->_Core['isAdmin'] && $data['postInfo']['uid']!=$this->mid ){
			$this->error( L('do_no_purview') );
		}
		/** 权限控制 **/
		
		if( $_POST['content'] ){
			
			/** 附件检测 **/
			$list = X('Xattach')->getAttach($_POST['attach']);
			unset($_POST['Xattach']);
			foreach($list as $key=>$value){
				$_POST['attach'][$key]   = $value['id'].'|'.$value['name'];
			}				
			
			if($data['postInfo']['istopic']){
				$topicdata['title'] = htmlspecialchars( $_POST['title'],ENT_QUOTES );
				$topicdata['tclass'] = intval( $_POST['tclass'] );
				$topicdata['tags'] = $this->topic->getTags( $_POST['tags'] );
				$topicdata['attach'] = ( $_POST['attach'] ) ?1:0;
				//投票贴
				if(isset($_POST['vote_id'])) {
					$topicdata['type'] = 1;
					M('vote')->where('id='.$_POST['vote_id'])->setField('fieldId', $data['postInfo']['tid']);
				}

				$this->topic->where('id='.$data['postInfo']['tid'] )->data($topicdata)->save();				
			}
			
			$savedata['muid']    = $this->mid;
			$savedata['mTime']   = time();
			$savedata['content'] = h( $_POST['content'] );
			$savedata['attach']  = serialize($this->__parseAttach($_POST['attach']));
			$this->post->where('id='.$intPid )->data($savedata)->save();
			$this->assign( 'jumpUrl',U('bbs/Index/detail',array('id'=>$data['postInfo']['tid'])) );
			$this->success( L("do_edit_success") );			
		}

	}
	
	private function __parseAttach($data){
		$result = array ();
		foreach ( $data as $key => $value ) {
			$temp = explode ( '|', $value );
			$result [$key] ['id'] = $temp [0];
			$result [$key] ['name'] = $temp [1];
		}
		return $result;
	}
	
	function dodel(){
		$intTid = intval($_POST['tid']);
		$data['postInfo'] = $this->post->getPostInfo( $intTid );

		/** 权限控制  **/
		$this->class = $data['postInfo']['board'];
		$this->boardPurview();   //载入权限控制器
		if(!$this->_Core['isAdmin'] ){
			$this->error( L('do_no_purview') );
		}
		/** 权限控制 **/		
		
		if($data['postInfo']['istopic']){
			M('bbs_classify')->where("tid=".$data['postInfo']['tid'])->delete();
			$this->topic->where("id=".$data['postInfo']['tid'])->delete();
			$this->post->where("tid=".$data['postInfo']['tid'])->delete();
			$this->credit->set($data['postInfo']['tuid'],'bbs_topic_del');
			echo '1';			
		}else{
			$this->post->setField('isdel',1,"id=".$intTid);
			$this->credit->set($data['postInfo']['uid'],'bbs_post_del');
			//$this->topic->setDec("replycount","id=".$data['postInfo']['tid']);
			echo '2';
		}	
	}
	
	function doAdminStatus(){
		$intTid = intval($_POST['tid']);
		$status = intval($_POST['status']);
		$statusMessage = ($status==1)? L('set') : L('cancel');
		
		$topicInfo = $this->topic->getTopic($intTid);
		
		/** 权限控制  **/
		$this->class = $_POST['board'];
		$this->boardPurview(true);   //载入权限控制器
		/** 权限控制 **/
		
		switch ($_POST['type']){
			case 'dist':   //精华
				$message = L('thread_soul');
				$result = $this->topic->setAdminStatus($this->class,$intTid,'dist',$status);
				if($result){ //积分
					if( $status=='1'){
						$this->credit->set($topicInfo['uid'],'bbs_topic_dist');
					}else if($status=='0'){
						$this->credit->set($topicInfo['uid'],'bbs_topic_undist');
					}
				}
			break;
			
			case 'alltop':
				$message = L('thread_all_top');
				if( $this->_Core['isWebAdmin'] ){
					$result = $this->topic->setAdminStatus($this->class,$intTid,'top',$status);
				}else{
					$result = false;
				}
			break;
			
			case 'top':    //置顶
				$message = L('thread_top');
				$result = $this->topic->setAdminStatus($this->class,$intTid,'top',$status);
			break;
			
			case 'lock':  //锁定
				$message = L('thread_lock');
				$result = $this->topic->setAdminStatus($this->class,$intTid,'lock',$status);
			break;
		}
		$message = $statusMessage.$message;
		if($result){
			$this->success($message.L('success'));
		}else{
			$this->success($message.L('error'));
		}
	}
}
?>